package com.shiwaixiangcun.customer.module.ticket

import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterMyTicket
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.CommonListCallBack
import com.shiwaixiangcun.customer.entity.CommonObjCallBack
import com.shiwaixiangcun.customer.entity.MyTicketInfo
import com.shiwaixiangcun.customer.entity.TicketInvalid
import com.shiwaixiangcun.customer.network.StringDialogCallBack
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import kotlinx.android.synthetic.main.activity_my_tickets.*
import kotlinx.android.synthetic.main.top_bar_white.*
import me.bakumon.statuslayoutmanager.library.OnStatusChildClickListener
import me.bakumon.statuslayoutmanager.library.StatusLayoutManager
import java.util.*

/**
 * 我的车票页面 (购买的车票汇总)
 */

class MyTicketsActivity : BaseActivity() {

    private var mCurrentPage = 0
    private var mPageSize = 1

    private var mAdapter: AdapterMyTicket? = null
    private var mDataList: MutableList<AdapterMyTicket.MyTicketSection>? = null
    private var mHeaderView: View? = null
    private var strToken: String? = null

    private var statusLayoutManager: StatusLayoutManager? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_my_tickets)
        initEmptyView()
        initViewAndEvent()
        initTicketData()
    }

    private fun initEmptyView() {

        val emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_no_data, null, false)
        emptyView.findViewById<TextView>(R.id.tv_prompt).text = resources.getString(R.string.empty_ticket)
        statusLayoutManager = StatusLayoutManager.Builder(rv_ticket)
                .setEmptyLayout(emptyView)
                .setDefaultLayoutsBackgroundColor(Color.WHITE)
                .setErrorLayout(R.layout.layout_error)
                .setOnStatusChildClickListener(object : OnStatusChildClickListener {
                    override fun onErrorChildClick(p0: View?) {
                        initTicketData()
                    }

                    override fun onEmptyChildClick(p0: View?) {
                    }

                    override fun onCustomerChildClick(p0: View?) {
                    }
                })
                .build()
    }

    private fun initTicketData() {
        val strToken = AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "") as String

        OkGo.get<String>(GlobalApi.myTicket)
                .params("access_token", strToken)
                .execute(object : StringDialogCallBack(this) {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonListCallBack<MyTicketInfo>>() {}.type
                        val responseEntity = Gson().fromJson<CommonListCallBack<MyTicketInfo>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {


                                refreshLayout.finishRefresh()
                                if (responseEntity.data.isNotEmpty()) {
                                    responseEntity.data
                                            .map { AdapterMyTicket.MyTicketSection(it) }
                                            .forEach { mDataList?.add(it) }
                                    statusLayoutManager?.showSuccessLayout()
                                    mAdapter?.notifyDataSetChanged()
                                } else {


                                }


                            }
                            else -> {
                                initTicketInvalidData(false)
                                showToastShort("请求数据失败")
                            }


                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        initTicketInvalidData(false)
                    }

                })

    }

    /**
     * 请求已经失效车票
     */

    private fun initTicketInvalidData(isLoadMore: Boolean) {

        OkGo.get<String>(GlobalApi.myTicketInvalid)
                .params("access_token", strToken)
                .params("page.pn", mCurrentPage)
                .params("page.size", mPageSize)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonObjCallBack<TicketInvalid>>() {}.type
                        val responseEntity = Gson().fromJson<CommonObjCallBack<TicketInvalid>>(response?.body(), type)
                        when (responseEntity.responseCode) {
                            1001 -> {


                                if (responseEntity.data.elements.isNotEmpty()) {
                                    statusLayoutManager?.showSuccessLayout()
                                    val header: AdapterMyTicket.MyTicketSection = AdapterMyTicket.MyTicketSection(true, "未使用")
                                    mDataList?.add(header)
                                    responseEntity.data.elements
                                            .map { AdapterMyTicket.MyTicketSection(it) }
                                            .forEach { mDataList?.add(it) }


                                    mAdapter?.notifyDataSetChanged()
                                } else {
                                    statusLayoutManager?.showEmptyLayout()
                                    return
                                }

                            }
                            else -> {
                                showToastShort("请求数据失败")
                            }


                        }
                    }

                })

    }

    private fun initViewAndEvent() {
        tv_page_name.text = "我的车票"
        strToken = AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "") as String
        mCurrentPage = GlobalConfig.first_page
        mPageSize = GlobalConfig.page_size
        back_left.setOnClickListener { finish() }
        mDataList = ArrayList()
        mAdapter = AdapterMyTicket(mDataList)
        rv_ticket.layoutManager = LinearLayoutManager(this)
        rv_ticket.adapter = mAdapter

        mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.header_ticket, null, false)
        mAdapter!!.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, _, position ->
            val item = adapter.data[position] as AdapterMyTicket.MyTicketSection
            if (item.isHeader) {
                return@OnItemClickListener
            } else {
                val bundle = Bundle()
                bundle.putString("ticketOrderId", item.t.orderId)
                bundle.putString("ticketStatus", item.t.status)
                bundle.putString("number", "")
                bundle.putBoolean("fromItem", true)
                readyGo(TicketDetailActivity::class.java, bundle)

            }
        }


        refreshLayout.setOnRefreshListener {
            mDataList?.clear()
            initTicketData()
        }
    }
}
